package com.tarena.lbs.business.rpc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.business.api.StoreApi;
import com.tarena.lbs.business.api.pojo.dto.StoreDTO;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * activity 店铺服务API实现类
 */
@Slf4j
@DubboService
@Service
public class StoreApiImpl implements StoreApi {

    @Autowired
    private StoreMapper storeMapper;


    /**
     * 根据区域查询店铺
     */
    @Override
    public List<StoreDTO> getStoreByCity(List<Long> cityIdList, Integer level) {
        log.debug("根据区域查询店铺，查询参数: cityIdList={}, level={}", cityIdList, level);
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();

        // 默认排除已删除的店铺
        queryWrapper.ne("store_status", 2);

        // 检查参数有效性
        if(level != null && cityIdList != null && !cityIdList.isEmpty()){
            if(level == 1){
                queryWrapper.in("province_id", cityIdList);
                log.debug("按省级ID查询，provinceIds: {}", cityIdList);
            } else if(level == 2){
                queryWrapper.in("city_id", cityIdList);
                log.debug("按市级ID查询，cityIds: {}", cityIdList);
            } else if(level == 3){
                queryWrapper.in("area_id", cityIdList);
                log.debug("按区级ID查询，areaIds: {}", cityIdList);
            } else {
                log.warn("区域级别无效: {}, 有效范围[1-3]", level);
            }
        } else {
            // 记录更详细的警告信息，包括调用堆栈摘要
            String stackTrace = Arrays.stream(Thread.currentThread().getStackTrace())
                    .limit(5)
                    .map(StackTraceElement::toString)
                    .collect(Collectors.joining("\n"));
            log.warn("区域查询参数不完整：level={}, cityIdList={}\n调用栈: {}",
                    level, cityIdList, stackTrace);
        }

        List<StorePO> poList = storeMapper.selectList(queryWrapper);
        log.debug("区域查询结果数量：{}", poList != null ? poList.size() : 0);
        return poList.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public List<StoreDTO> getStoresByBusinessId(Integer businessId) {
        log.info("根据商家ID查询店铺列表，businessId: {}", businessId);
        try {
            if (businessId == null) {
                return new ArrayList<>();
            }

            List<StorePO> storePOs = storeMapper.selectList(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<StorePO>()
                            .eq("business_id", businessId)
                            .eq("store_status", 0) // 只查询启用状态的店铺
            );
            return storePOs.stream().map(this::convertToDTO).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("根据商家ID查询店铺列表失败，businessId: {}, error: {}", businessId, e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    public Boolean checkStoreExists(Integer storeId) {
        log.info("检查店铺是否存在，storeId: {}", storeId);
        try {
            if (storeId == null) {
                return false;
            }
            StorePO storePO = storeMapper.selectById(storeId);
            return storePO != null && storePO.getStoreStatus() == 0;
        } catch (Exception e) {
            log.error("检查店铺是否存在失败，storeId: {}, error: {}", storeId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public StoreDTO getStoreById(Integer shopId) {
        return null;
    }

    @Override
    public List<StoreDTO> getStoresByIds(String string) {
        return List.of();
    }

    /**
     * 将PO对象转换为DTO对象
     */
    private StoreDTO convertToDTO(StorePO po) {
        StoreDTO dto = new StoreDTO();
        BeanUtils.copyProperties(po, dto);
        return dto;
    }


}